import AccreditDia from '@/components/accreditDia/AccreditDia'
import NoPermissionTem from '@/components/antd-comp/NoPermission'
import ListEmpty from '@/components/antd-comp/empty'
import TabsDropComponent from '@/components/antd-comp/tabs'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { Accordion } from '@/components/bs-ui/accordion'
import { getPublished_list } from '@/controllers/API/assistant'
import { getToolVersion } from '@/controllers/API/tools'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { usePluginStore } from '@/store/pluginStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { Input } from 'antd'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocation, useNavigate } from 'react-router-dom'
import Edition from './components/Edition'
import ToolItem from './components/ToolItem'
import { filterPublishToolNames } from './constants'
import './css/tabTools.less'

export default function TabTools({ select = null, onSelect }) {
  const { t } = useTranslation()
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = [t('menu.plugin')]
  useRouteStoreHook(routeNames)

  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const navigate = useNavigate()
  const [keyword, setKeyword] = useState(' ')
  const [allData, setAllData] = useState([])
  const { pluginBuriedEvent } = useBuriedEvent()
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  const { setPluginDetail } = usePluginStore()

  const [type, setType] = useState('') // '' add edit
  /* Spin 参数 */
  const [dataLoading, setDataLoading] = useState(true)

  // select type
  const [typeList, setTypeList] = useState([])
  const [selected, setSelected] = useState('')

  const { loadDictOptions } = useDictStore()
  const initData = (type = 'category') => {
    loadDictOptions(type).then(res => {
      res.unshift({
        value: '',
        label: '全部类型',
        id: 0
      })
      setTypeList(res)
    })
  }

  const loadData = (_type, categoryCode: string): any => {
    if (!hasFuncPermission([Func.tools.query])) {
      return
    }
    setDataLoading(true)
    setAllData([])
    let is_preset = null
    let is_custom = null
    if (type === 'edit') {
      is_custom = true
    } else {
      is_custom = false
      is_preset = true
    }
    getPublished_list(is_preset, is_custom, categoryCode || null)
      .then(res => {
        let temp = []
        if (type === 'edit') {
          temp = res?.list
        } else {
          temp = res?.list.filter(item => filterPublishToolNames.includes(item.name))
        }
        setAllData(temp)
        setKeyword('')
        setDataLoading(false)
      })
      .catch(err => {
        console.log(err)
        setDataLoading(false)
      })
  }

  const handeleTypeSelected = item => {
    pluginBuriedEvent({
      page: '插件页面',
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: keyword, 类型: item.value })
    })
    setSelected(item.value)
    loadData('custom', item.value)
  }

  /* 判断是否查看回退 展示版本选择弹窗 */
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const version = searchParams.get('version')
  useEffect(() => {
    /* 判断缓存区分自定义列表 */
    const tool_id = localStorage.getItem('plugin_tool_id')
    if (version && tool_id) {
      localStorage.setItem('plugin_tool_id', '')
      setType('edit')
      return
    }
    loadData(type === '' ? 'default' : 'custom', type === '' ? '' : selected)
    //initData()
  }, [type])

  const options = useMemo(() => {
    return (
      allData?.filter(
        el =>
          el.name.toLowerCase().includes(keyword.toLowerCase()) ||
          el.description.toLowerCase().includes(keyword.toLowerCase())
      ) || []
    )
  }, [keyword, selected, allData])

  const handleEdit = (event, el) => {
    event.stopPropagation()
    pluginBuriedEvent({
      page: '自定义插件页面',
      event_name: '【编辑】按钮',
      data_id: el.id
    })
    if (!hasFuncPermission([Func.tools.edit])) {
      return
    }
    setPluginDetail(el)
    navigate(`/plugin/create/${el.id}`)
  }
  /* 版本 */
  const pageinfo = {
    size: 10,
    pageNum: 1,
    total: 500
  }
  const fathInfo = {
    id: '',
    tool_id: ''
  }
  const [fathInfoAll, SetFathInfoAll] = useState(fathInfo)
  const [RecordPage, SetRecordPage] = useState(pageinfo)
  const [RecordsHid, SetRecordsHid] = useState(false)
  const onRecords = (event, el) => {
    if (!hasFuncPermission([Func.tools.version])) {
      return
    }
    setrecordList([])
    SetFathInfoAll({
      ...el
    })
    event.stopPropagation()
    pluginBuriedEvent({
      page: '自定义插件页面',
      event_name: '【版本记录】按钮',
      data_id: el.id
    })
    localStorage.setItem('plugin_tool_id', el.tool_id)
    getVersions(el.tool_id)
    // SetRecordPage({ ...RecordPage, pageNum: 1 })
  }

  const [recordList, setrecordList] = useState([])
  const recordPage = e => {
    console.log(e, 'e')
    SetRecordPage({ ...RecordPage, pageNum: 1 })
    /* updata list */
  }
  /* 版本 = list */
  const getVersions = id => {
    getToolVersion(id).then(res => {
      const list = res?.list || []
      const processedList = list.map(item => {
        item.label = item.version
        item.childrenItem = item.children
        delete item.children
        return {
          ...item
        }
      })
      setrecordList(processedList)
      SetRecordsHid(true)
    })
  }
  /* 查看版本 */
  const handleVersion = e => {
    setPluginDetail({
      ...fathInfoAll,
      ...e,
      hidType: 'listSee'
    })
    pluginBuriedEvent({
      page: '版本记录弹窗',
      event_name: '【查看】按钮',
      data_id: fathInfoAll.id
    })
    navigate(`/plugin/create/${fathInfoAll.id}`)
  }
  const closeFun = () => {
    SetRecordPage({ ...RecordPage, pageNum: 1 })
    SetRecordsHid(false)
  }
  /* 权限 */
  const [accredit, setAccredit] = useState(false)

  if (!hasFuncPermission([Func.tools.menu], false)) {
    return <NoPermissionTem />
  }
  return (
    // <div className="relative flex h-full bg-[#f5f7fb] p-[32px]" onClick={e => e.stopPropagation()}>
    <div className="relative flex h-full bg-[#f5f7fb] p-[32px]">
      <div className="relative flex h-full w-full overflow-y-scroll rounded-[6px] bg-[#fff] scrollbar-hide">
        <div className="plugin-border-right w-[25%] min-w-[200px] max-w-[400px] p-6">
          <h1>{t('tools.toolList')}</h1>
          <Input
            size="large"
            placeholder={t('tools.search')}
            prefix={
              <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle
                  cx="6.96436"
                  cy="6.96484"
                  r="5"
                  stroke="black"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M10.5 10.5L14.0355 14.0355"
                  stroke="black"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            }
            className="mt-6"
            onChange={e => {
              pluginBuriedEvent({
                page: '插件页面',
                event_name: '搜索条件',
                detail: JSON.stringify({ 搜索条件: e.target.value, 类型: selected })
              })
              setKeyword(e.target.value)
            }}
          />
          {/* <Button className="mt-4 w-full" onClick={() => navigate('/plugin/create/0')}>
            {t('create')}
            {t('tools.createCustomTool')}
          </Button> */}
          <ThemeBtn
            className="mt-4  w-full"
            style={{ height: '36px' }}
            onClick={() => {
              pluginBuriedEvent({
                page: '插件页面',
                event_name: '【创建自定义插件】按钮'
              })

              if (!hasFuncPermission([Func.tools.add])) {
                return
              }
              navigate('/plugin/create/0')
            }}
            shape="pill"
          >
            {t('create')}
            {t('tools.createCustomTool')}
          </ThemeBtn>
          <div className="mt-4">
            <div
              className={`hover:bg-plugin' flex cursor-pointer items-center gap-2 rounded-md px-4 py-2 transition-all duration-200 ${
                type === '' && 'bg-[#E0E7FF]'
              }`}
              style={{ height: '36px' }}
              onClick={() => {
                pluginBuriedEvent({
                  page: '插件页面',
                  event_name: '【内置插件】按钮'
                })
                setType('')
              }}
            >
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M8 16H3V4H14V7"
                  stroke="#232E3E"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M12 16H14.5C15.8807 16 17 14.8807 17 13.5V13.5C17 12.1193 15.8807 11 14.5 11H8"
                  stroke="#232E3E"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
                <path
                  d="M10 9L8 11L10 13"
                  stroke="#232E3E"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
              <span style={{ fontSize: '14px', fontWeight: 400 }}>{t('tools.builtinTools')}</span>
            </div>
            <div
              className={`hover:bg-plugin' mt-4 flex cursor-pointer items-center gap-2 rounded-md px-4 py-2 transition-all duration-200 ${
                type === 'edit' && 'bg-[#E0E7FF]'
              }`}
              style={{ height: '36px' }}
              onClick={() => {
                pluginBuriedEvent({
                  page: '插件页面',
                  event_name: '【自定义插件】按钮'
                })
                setType('edit')
              }}
            >
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M9.10628 2.56826C9.45106 1.81058 10.5489 1.81058 10.8937 2.56826L12.4734 6.03968C12.6156 6.35217 12.9171 6.56673 13.2644 6.60264L17.123 7.00156C17.9651 7.08863 18.3044 8.11144 17.6753 8.66678L14.7931 11.2112C14.5336 11.4402 14.4184 11.7874 14.4909 12.122L15.296 15.84C15.4717 16.6515 14.5835 17.2836 13.8499 16.8692L10.4889 14.9703C10.1863 14.7993 9.81368 14.7993 9.51112 14.9703L6.15012 16.8692C5.41654 17.2836 4.52834 16.6515 4.70405 15.84L5.50909 12.122C5.58156 11.7874 5.46641 11.4402 5.20695 11.2112L2.32469 8.66677C1.69561 8.11144 2.03487 7.08863 2.87704 7.00156L6.73559 6.60264C7.08294 6.56673 7.3844 6.35217 7.52661 6.03968L9.10628 2.56826Z"
                  fill="black"
                />
              </svg>
              <span style={{ fontSize: '14px', fontWeight: 400 }}>{t('tools.customTools')}</span>
            </div>
          </div>
        </div>
        {/* cont */}
        <div
          className={
            type == 'edit' && typeList.length
              ? 'paddtop_tabtools h-full flex-1 overflow-auto bg-[#fff] px-6 pb-6 scrollbar-hide'
              : 'paddtopDef_tabtools h-full flex-1 overflow-auto bg-[#fff] px-6 pb-6 scrollbar-hide'
          }
          style={{ position: 'relative' }}
        >
          {/* 筛选 */}
          <div className="select-type absolute top-[0px] z-[49] bg-[#fff]">
            {type == 'edit' && typeList.length ? (
              <TabsDropComponent
                className="tab-tools-tabs"
                list={typeList}
                value={selected}
                tabsDropFun={handeleTypeSelected}
              ></TabsDropComponent>
            ) : null}
          </div>
          {/* 内容 */}
          {dataLoading ? (
            <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
              <span className="loading loading-infinity loading-lg"></span>
            </div>
          ) : (
            <Accordion type="single" collapsible className="h-full w-full overflow-auto scrollbar-hide">
              {options.length ? (
                options.map(el => (
                  <ToolItem
                    key={el.id}
                    type={type}
                    select={select}
                    data={el}
                    onSelect={onSelect}
                    onEdit={e => handleEdit(e, el)}
                    onRecords={e => onRecords(e, el)}
                    onAccreditDia={() => {
                      setAccredit(true)
                    }}
                  ></ToolItem>
                ))
              ) : (
                <ListEmpty />
              )}
            </Accordion>
          )}
        </div>
      </div>
      {/* 版本记录 */}
      {RecordsHid ? (
        <Edition
          recordList={recordList}
          RecordPage={RecordPage}
          recordPage={e => {
            recordPage(e)
          }}
          RadioChang={e => {
            console.log(e, 'RadioChang')
          }}
          closeFun={closeFun}
          handleVersion={e => {
            handleVersion(e)
          }}
        ></Edition>
      ) : null}

      {/* 分配权限 */}
      {accredit && (
        <AccreditDia
          cancel={() => {
            setAccredit(false)
          }}
          submit={() => {
            setAccredit(false)
          }}
        />
      )}
    </div>
  )
}
